var trade_manage_state = 'trade_list';
var trade_list_page = 0;
var trade_list_pageSize = 10;
var trade_list = [];
var current_page = 1;
async function trade_manage_init() {
    trae_board_state = 'trade_list';
    trade_list_page = 0;
    trade_list = [];
    //更新交易信息
    float_text('正在获取交易列表');
    await update_trade_list_page();
    await update_trade_list();
    draw_trade_manage();

}

async function displayTradeData() {
    document.querySelector('.trade-manage-content #jump-page input').value = current_page;
    const table_body = document.querySelector(".trade-manage-content #table-body");
    var data = '';
    for (var i = 0; i < trade_list.length; i++) {
        var item = trade_list[i];
        var status = ['机构审核中',
            '自动审核通过',
            '机构审核通过',
            '公安审核中',
            '公安审核通过',
            '立项调查中',
            '存在洗钱嫌疑',
            '无洗钱嫌疑',
        ];
        for (var j = 0; j < status.length; j++) {
            if (j == 0 || j == 3 || j == 5 || j == 6) {
                status[j] = '<p style="color:rgb(255,0,0); margin:0; padding:0;">' + status[j] + '</p>';
            }
        }
        data += `
            <tr>
                <td>${item.id}</td>
                <td>${item.time}</td>
                <td>${item.trader}</td>
                <td>${item.payee}</td>
                <td>${item.money}CNY</td>
                <td>${status[item.status]}</td>
                <td>
                    <div id='view-detail' class='operate-button icon-chakan'></div>
                    <div id='edit-button' class='operate-button icon-bianji1'></div>
                    <div id='delete-button' class='operate-button icon-shanchu'></div>
                </td>
            </tr>
            `;
    }
    table_body.innerHTML = data;
    var tempList = table_body.querySelectorAll('#view-detail');
    //查看详情
    for (var i = 0; i < tempList.length; i++) {
        tempList[i].setAttribute('index', i);
        add_float_tip(tempList[i], '查看详细信息');
        tempList[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            trade_manage_state = 'trade_detail';
            //更新交易信息面板的内
            var status = ['机构审核中',
                '自动审核通过',
                '机构审核通过',
                '公安审核中',
                '公安审核通过',
                '立项调查中',
                '存在洗钱嫌疑',
                '无洗钱嫌疑',
            ];
            for (var j = 0; j < status.length; j++) {
                if (j == 0 || j == 3 || j == 5 || j == 6) {
                    status[j] = '<p style="color:rgb(255,0,0); margin:0; padding:0;">' + status[j] + '</p>';
                }
            }
            var content = `
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">ID :</div>
                        <input readonly value=${trade_list[index].id} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">交易时间 :</div>
                        <input readonly value=${trade_list[index].time} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">付款方 :</div>
                        <input readonly value=${trade_list[index].trader} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">收款方 :</div>
                        <input readonly value=${trade_list[index].payee} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">交易金额 :</div>
                        <input readonly value=${trade_list[index].money} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">编辑人 :</div>
                        <input readonly value=${trade_list[index].userId || 'NULL'} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">审核状态 :</div>
                        <input readonly value=${status[trade_list[index].status]} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                `;
            document.querySelector('.trade-manage-content .trade-manage-second #trade-detail').innerHTML = content;
            draw_trade_manage();
        });
    }
    tempList = table_body.querySelectorAll('#edit-button');
    //编辑
    for (var i = 0; i < tempList.length; i++) {
        tempList[i].setAttribute('index', i);
        add_float_tip(tempList[i], '编辑');
        tempList[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            trade_manage_state = 'trade_edit';
            //更新交易编辑面板的内容
            var status = ['机构审核中',
                '自动审核通过',
                '机构审核通过',
                '公安审核中',
                '公安审核通过',
                '立项调查中',
                '存在洗钱嫌疑',
                '无洗钱嫌疑',
            ];
            for (var j = 0; j < status.length; j++) {
                if (j == 0 || j == 3 || j == 5 || j == 6) {
                    status[j] = '<p style="color:rgb(255,0,0)">' + status[j] + '</p>';
                }
            }
            var content = `
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">ID :</div>
                        <input id='id-input' readonly value=${trade_list[index].id} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">交易时间 :</div>
                        <input id='time-input' readonly value=${trade_list[index].time} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">付款方 :</div>
                        <input id='trader-input' value=${trade_list[index].trader} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">收款方 :</div>
                        <input id='payee-input' value=${trade_list[index].payee} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">交易金额 :</div>
                        <input id='money-input' value=${trade_list[index].money} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">编辑人 :</div>
                        <input readonly value=${trade_list[index].userId || 'NULL'} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">审核状态 :</div>
                        <input readonly value=${status[trade_list[index].status]} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div>
                        <div id="cancel-edit-trade" class="rect_button icon-guifandaohanglancha"></div>
                        <div id="commit-edit-trade" class="rect_button icon-zhengque"></div>
                    </div>
                `;
            document.querySelector('.trade-manage-content .trade-manage-third').innerHTML = content;
            add_float_tip(document.querySelector('.trade-manage-content .trade-manage-third #cancel-edit-trade'), '取消编辑');
            add_float_tip(document.querySelector('.trade-manage-content .trade-manage-third #commit-edit-trade'), '完成');
            document.querySelector('.trade-manage-content .trade-manage-third #cancel-edit-trade').addEventListener('click',
                function () {
                    trade_manage_state = 'trade_list';
                    draw_trade_manage();
                }
            );
            document.querySelector('.trade-manage-content .trade-manage-third #commit-edit-trade').addEventListener('click',
                async function () {
                    const table = document.querySelector('.trade-manage-content .trade-manage-third');

                    //通过接口传递修改数据
                    const api = 'http://47.109.78.200:10010/transaction/updateTransaction';
                    data = {
                        id: table.querySelector('#id-input').value,
                        // time: table.querySelector('#time-input').value,
                        payee: table.querySelector('#payee-input').value,
                        trader: table.querySelector('#trader-input').value,
                        money: table.querySelector('#money-input').value,
                        userId: getCookieValue('login_userId'),
                    };
                    console.log(data);
                    await fetchWithTimeout(api, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            token: getCookieValue('token'),
                        },
                        body: JSON.stringify(data),
                    }).then(response => response.json()).
                        then(data => {
                            if (data['code'] == 100) {
                                float_text('修改成功');
                            } else {
                                float_text('修改失败');
                            }
                            if (data['msg'] == '用户未登入') {
                                exit_login();
                                return;
                            }
                        }).catch(error => {
                            console.log(error);
                        })
                    trade_manage_state = 'trade_list';
                    await update_trade_list();
                    draw_trade_manage();
                }
            );
            trade_manage_state = 'trade_edit';
            draw_trade_manage();
        });
    }
    tempList = table_body.querySelectorAll('#delete-button');
    //删除
    for (var i = 0; i < tempList.length; i++) {
        tempList[i].setAttribute('index', i);
        add_float_tip(tempList[i], '删除');
        tempList[i].addEventListener('click', function () {
            var index = this.getAttribute('index');
            var content = `
                    <div style="background-color: #fff; padding: 20px 30px; font-size:26px; font-weight: lighter; border:none; border-radius:20px; overflow:hidden;">
                        <div style="margin: 0px 20px 40px 20px; color:rgb(0,0,0); font-weight: bold;">确认删除?</div>
                        <p style="margin: 10px 60px; font-size:22px;">ID : ${trade_list[index].id}</p>
                        <p style="margin: 10px 60px; font-size:22px;">交易时间 : ${trade_list[index].time}</p>
                        <p style="margin: 10px 60px; font-size:22px;">付款人 : ${trade_list[index].trader}</p>
                        <p style="margin: 10px 60px; font-size:22px;">收款人 : ${trade_list[index].payee}</p>
                        <p style="margin: 10px 60px; font-size:22px;">交易金额 : ${trade_list[index].money}</p>
                        <button class='fullScreen-button' id="confirm-delete" index=${index} style="display:inline; width:90%; height:45px; margin: 30px 20px 0 20px; font-size:22px;">确认</button>
                        <button class='fullScreen-button2' style="display:inline; width:90%; height:45px; margin: 30px 20px 0 20px; font-size:22px;" onclick="hideFullScreenTip()">取消</button> 
                    </div>
                    `;
            showFullScreenTip(content);
            document.querySelector('.fullScreen-tip #confirm-delete').addEventListener('click',
                async function () {
                    //删除该交易
                    const api = 'http://47.109.78.200:10010/transaction/deleteTransactionById';
                    data = {
                        transactionId: trade_list[index].id,
                    };
                    const url = getRequestUrl(data, api);
                    await fetchWithTimeout(url, {
                        method: 'delete',
                        headers: {
                            'Content-Type': 'application/json',
                            'token': getCookieValue('token'),
                        },
                        // body: JSON.stringify(data),
                    }).then(response => response.json())
                        .then(data => {
                            if (data['code'] == 100) {
                                float_text('删除成功');
                            } else {
                                if (data['msg'] == '用户未登入') {
                                    exit_login();
                                    return;
                                }
                                float_text('删除失败');
                            }
                            update_trade_list();
                        }).catch(error => {
                            console.log(error);
                        });
                    hideFullScreenTip();
                }
            );

        });
    }
}

async function update_trade_list() {
    await update_trade_list_page();
    current_page = Math.min(current_page, trade_list_page);
    //从接口获取数据...
    trade_list = [];
    const api = 'http://47.109.78.200:10010/transaction/selectAll';
    const data = {
        pageNum: current_page,
        pageSize: trade_list_pageSize
    };
    const url = getRequestUrl(data, api);
    await fetchWithTimeout(url, {
        headers: {
            token: getCookieValue('token'),
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data['code'] == 100) {
                if (data['msg'] == '用户未登录') {
                    exit_login();
                } else if (data['msg'] == '查询成功') {
                    trade_list = data['data'];
                }
                return;
            }
            float_text('查询交易时出现未知错误');
        }).catch(error => {
            console.log(error);
        });
    //更新列表的显示内容
    displayTradeData();
}

async function update_trade_list_page() {
    const api = 'http://47.109.78.200:10010/transaction/selectTransactionCount';
    await fetchWithTimeout(api, {
        headers: {
            token: getCookieValue('token'),
        }
    }).then(response => response.json())
        .then(data => {
            console.log('获取交易数量的请求结果:');
            console.log(data);
            if (data['code'] == 100) {
                trade_list_page = Math.ceil(data['data'] / trade_list_pageSize);
            }
            if (data['msg'] == '用户未登入') {
                exit_login();
                return;
            }
        }).catch(error => {
            console.log(error);
        })
    document.querySelector('.trade-manage-content .trade-manage-first #jump-page .page-num').innerHTML = `/ ${trade_list_page}`;
}

function draw_trade_manage() {
    document.querySelector('.trade-manage-content .trade-manage-first').style['display'] = 'none';
    document.querySelector('.trade-manage-content .trade-manage-second').style['display'] = 'none';
    document.querySelector('.trade-manage-content .trade-manage-third').style['display'] = 'none';
    document.querySelector('.trade-manage-content .trade-manage-fourth').style['display'] = 'none';

    switch (trade_manage_state) {
        case 'trade_list':
            document.querySelector('.trade-manage-content .trade-manage-first').style['display'] = 'block'; break;
        case 'trade_detail':
            document.querySelector('.trade-manage-content .trade-manage-second').style['display'] = 'block'; break;
        case 'trade_edit':
            document.querySelector('.trade-manage-content .trade-manage-third').style['display'] = 'block'; break;
        case 'trade_add':
            document.querySelector('.trade-manage-content .trade-manage-fourth').style['display'] = 'block'; break;
        default:
            document.querySelector('.trade-manage-content .trade-manage-first').style['display'] = 'block';
            break;
    }
}
draw_trade_manage();
//添加悬浮提示
add_float_tip(document.querySelector('.trade-manage-content .trade-manage-first #prev-page'), "上一页");
add_float_tip(document.querySelector('.trade-manage-content .trade-manage-first #next-page'), "下一页");
add_float_tip(document.querySelector('.trade-manage-content .trade-manage-first #add-trade'), "新增一条交易记录");
add_float_tip(document.querySelector('.trade-manage-content .trade-manage-second #return-button'), "返回列表");

//详情页面的返回列表按钮
document.querySelector('.trade-manage-content .trade-manage-second #return-button').addEventListener('click',
    function () {
        trade_manage_state = 'trade_list';
        draw_trade_manage();
    }
);

//新增交易记录
document.querySelector('.trade-manage-content .trade-manage-first #add-trade').addEventListener('click',
    function () {
        var content = `
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">付款方 :</div>
                        <input id='trader-input'class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">收款方 :</div>
                        <input id='payee-input'class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">交易金额 :</div>
                        <input id='money-input'class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div style="display: flex; margin: 20px 0;">
                        <div class="info-show">编辑人 :</div>
                        <input id='userId-input'readonly value=${getCookieValue('login_userId')} class='muti-line-input' type="text"
                            style="display: inline-block; margin: 0 30px;font-size: 22px; width: 75%; height: 30px;">
                    </div>
                    <div>
                        <div id="cancel-add-trade" class="rect_button icon-guifandaohanglancha"></div>
                        <div id="commit-add-trade" class="rect_button icon-zhengque"></div>
                    </div>
                `;

        document.querySelector('.trade-manage-content .trade-manage-fourth').innerHTML = content;
        add_float_tip(document.querySelector('.trade-manage-content .trade-manage-fourth #cancel-add-trade'), '取消');
        add_float_tip(document.querySelector('.trade-manage-content .trade-manage-fourth #commit-add-trade'), '确认添加');
        document.querySelector('.trade-manage-content .trade-manage-fourth #cancel-add-trade').addEventListener('click',
            function () {
                trade_manage_state = 'trade_list';
                draw_trade_manage();
            }
        );
        document.querySelector('.trade-manage-content .trade-manage-fourth #commit-add-trade').addEventListener('click',
            async function () {
                const tab = document.querySelector('.trade-manage-content .trade-manage-fourth');
                data = {
                    trader: tab.querySelector('#trader-input').value,
                    payee: tab.querySelector('#payee-input').value,
                    money: tab.querySelector('#money-input').value,
                    userId: tab.querySelector('#userId-input').value,
                    authority: 1,
                };
                if (data['trader'] == '' ||
                    data['payee'] == '' ||
                    data['money'] == '' ||
                    data['userId'] == ''
                ) {
                    float_text('输入框不可留空');
                    return;
                }
                //通过接口传递添加的数据
                const api = 'http://47.109.78.200:10010/transaction/insertTransaction';
                // const url = getRequestUrl(data, api);
                await fetchWithTimeout(api, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        token: getCookieValue('token'),
                    },
                    body: JSON.stringify(data)
                }).then(response => response.json())
                    .then(data => {
                        console.log('添加交易的请求结果:');
                        console.log(data);
                        if (data['code'] == 100) {
                            float_text('添加成功');
                        } else {
                            float_text('添加失败');
                        }
                        if (data['msg'] == '用户未登入') {
                            exit_login();
                            return;
                        }
                    }).catch(error => {
                        float_text('出现异常');
                        console.log(error);
                    });
                trade_manage_state = 'trade_list';
                await update_trade_list_page();
                await update_trade_list();
                draw_trade_manage();
            }
        );
        trade_manage_state = 'trade_add';
        draw_trade_manage();
    }
);

//上一页
document.querySelector('.trade-manage-content .trade-manage-first #prev-page').addEventListener('click',
    async function () {
        await update_trade_list_page();
        if (current_page > 1) {
            current_page--;
            update_trade_list();
        }
    }
);

//下一页
document.querySelector('.trade-manage-content .trade-manage-first #next-page').addEventListener('click',
    async function () {
        await update_trade_list_page();
        current_page = Math.min(current_page + 1, trade_list_page);
        await update_trade_list();
    }
);

//跳转
document.querySelector('.trade-manage-content .trade-manage-first #jump-page input').addEventListener('keydown',
    async function (event) {
        if (event.key == 'Enter') {
            await update_trade_list_page();
            if (!/^\d+$/.test(this.value)) {
                float_text("你输入的页码有误");
                this.value = '';
                return;
            }
            if (this.value < 1 || this.value > trade_list_page) {
                float_text("你输入的页码有误");
                this.value = '';
                return;
            }
            current_page = this.value;
            await update_trade_list();
            this.blur();
        }
    });
